﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BIUtils.GeoTaggingService;
using System.Net;
using System.Xml.Linq;
using System.Drawing;

namespace BIUtils
{
    public class GeoTagUtils
    {
        private readonly string Query = @"http://dev.virtualearth.net/REST/v1/Locations?output=xml&key={0}&query={1}";
        /// <summary>
        /// Gets the location.
        /// </summary>
        /// <param name="appToken">The app id.</param>
        /// <param name="address">The address.</param>
        /// <returns></returns>
        public KeyValuePair<double, double> GetGeocodeResponse(string appToken, string address)
        {
            var runQuery = string.Format(Query, appToken, address);
            using (var client = new WebClient())
            {
                try
                {
                    var response = client.DownloadString(runQuery);
                    var xDoc = XDocument.Parse(response);
                    XNamespace systemNs = "http://schemas.microsoft.com/search/local/ws/rest/v1";

                    var point = xDoc.Descendants(systemNs + "Point").FirstOrDefault();

                    var location = new KeyValuePair<double, double>(Convert.ToDouble(point.Element(systemNs + "Latitude").Value),
                                                                    Convert.ToDouble(point.Element(systemNs + "Longitude").Value));
                    return location;
                }
                catch
                {
                    //TODO: Log exception
                    return default(KeyValuePair<double, double>);
                }
            }
        }
    }
}
